package com.wjw.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wjw.entity.User;
import com.wjw.service.UserService;
import com.wjw.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT学习
 * -----------------------------------------------------
 * /user/**下的请求会,被会被JWTInterceptor拦截器:放行
 * -----------------------------------------------------
 * /xxx/**等所有路径下的请求,会被JWTInterceptor拦截器:拦截
 * 获取请求头中的token,并对token进行验证
 * 如果token合法,放行该请求
 * 如果token不合法,拦截该请求,并返回错误信息给前台
 * -----------------------------------------------------
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 1.JWTInterceptor会放行该请求
     * 使用postmand的GET请求测试：
     * 127.0.0.1:8081/user/login?name=wjw&password=123456
     * @param user
     * @return
     */
    @GetMapping("/user/login")
    public Map<String,Object> login(User user){
        log.info("用户名：[{}]",user.getName());
        log.info("密码：[{}]",user.getPassword());
        Map<String,Object> map = new HashMap<>();
        try {
            User userDB = userService.login(user);
            //根据payload生成JWT令牌(token)
            Map<String,String> payload = new HashMap<>();
            payload.put("userId",userDB.getId()+"");
            payload.put("userName",userDB.getName());
            //生成token
            String token = JwtUtils.createToken(payload);
            //返回给前台的数据
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    /**
     * 2.JWTInterceptor会拦截该请求,判断请求头中token的合法性
     * 使用postmand的Post请求测试：
     * 127.0.0.1:8081/zhzx/test
     * 并在header中传入token:aaa.bbb.ccc,如：
     * token : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6IndqdyIsImV4cCI6MTYzNjYxNTY3MSwidXNlcklkIjoiMSJ9.vpAzaYBTTYk5SJFe_A0nCPAnphCiKlYiuvqpVKR5Ahk
     * @return
     */
    @PostMapping("/zhzx/test")
    public Map<String,Object> test(HttpServletRequest request){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取请求头中的token
        String token = request.getHeader("token");
        DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
        //获取token组成相关信息
        String header = tokenInfo.getHeader();
        String payload = tokenInfo.getPayload();
        String signature = tokenInfo.getSignature();
        //获取保存在payload中的相关用户信息、token过期时间
        String userId = tokenInfo.getClaim("userId").asString();
        String userName = tokenInfo.getClaim("userName").asString();
        String expiresDate = dateFormat.format(tokenInfo.getExpiresAt());
        //日志输出相关信息
        log.info("token==========>：[{}]",token);
        log.info("header==========>：[{}]",header);
        log.info("payload==========>：[{}]",payload);
        log.info("signature==========>：[{}]",signature);
        log.info("userId==========>：[{}]",userId);
        log.info("userName==========>：[{}]",userName);
        log.info("expiresDate==========>：[{}]",expiresDate);
        //返回给前台的相关信息
        Map<String,Object> map = new HashMap<>();
        map.put("state",true);
        map.put("msg","请求成功666");
        return map;
    }
}
